// 监听scroll触发的function，控制顶部固定导航的显示
function changeBarDisplay(bar, num) {
    var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
    if (scrollTop >= num) {
        bar.style.display = 'block';
    } else {
        bar.style.display = 'none';
    }
};

function changeDisplayFun() {
    var topBar = document.getElementById('topBar');
    var leftBar = document.getElementsByClassName('left-nav-bar')[0];
    var loginBtn = document.getElementsByClassName('login-btn');
    var closeLoginBtn = document.getElementById('close-login-btn');
    var loginWindow = document.getElementById('top-login');
    window.addEventListener('scroll', function() {
        changeBarDisplay(topBar, 200);
        changeBarDisplay(leftBar, 850);
    });

    // 给登录按钮绑定点击事件，以及关闭按钮
    (function() {
        for (let i = 0; i < loginBtn.length; i++) {
            loginBtn[i].addEventListener('click', function() {
                loginWindow.style.display = 'flex';
            }, false);
        };

        closeLoginBtn.addEventListener('click', function() {
            loginWindow.style.display = 'none';
        }, false);
    })();
};

function searchFun() {
    var searchInp = document.getElementsByClassName('search');
    var searchBtn = document.getElementsByClassName('icon-sousuo');
    for (let i = 0; i < searchInp.length; i++) {
        searchInp[i].addEventListener('keydown', function(event) {
            if (event.keyCode == 13) {
                searchToBaidu(searchInp.value);
                searchInp.value = "";
            }
        });
        searchBtn[i].addEventListener('click', function() {
            searchToBaidu(searchInp.value);
            searchInp.value = "";
        })
    }
};


// 假装是ajax在请求后端，到时候可以直接请求自己的后端
function searchToBaidu(wordkey) {
    Ajax().get({
        url: 'http://www.baidu.com',
        data: {
            wd: wordkey
        },
        aysnc: true,
        success: function(res) {
            // console.log(res, '请求成功');
        },
        error: function() {
            // console.log('请求失败');
        }
    });
};


(function() {
    changeDisplayFun();
    searchFun();
})();